<template>
  <a-modal
    :title="id ? '编辑企业微信' : '新增企业微信'"
    :width="720"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :destroyOnClose="true"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="企业名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['name', {rules: [{ required: true, message: '请输入企业名称'}]}]"
          />
        </a-form-item>
        <a-form-item label="企业ID" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['corp_id', {rules: [{ required: true, message: '请输入企业ID'}]}]"
          />
        </a-form-item>
        <a-form-item label="应用密钥" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['secret', {rules: [{ required: true, message: '请输入应用密钥'}]}]"
          />
        </a-form-item>
        <a-form-item label="应用Token" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['token', {rules: [{ required: true, message: '请输入应用Token'}]}]"
          />
        </a-form-item>
        <a-form-item label="aes_key" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['aes_key', {rules: [{ required: true, message: '请输入企业aes_key'}]}]"
          />
        </a-form-item>
        <a-form-item label="弹窗背景图" :labelCol="labelCol" :wrapperCol="wrapperCol" extra="建议尺寸：760*600像素">
          <SelectImage :maxNum="1" :defaultList="defaultList"  @change="changeImage" v-decorator="['image_id']" />
        </a-form-item>
        <a-form-item label="欢迎语" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-textarea  :rows="6"
            v-decorator="['welcome_code']"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import _ from 'lodash'
import * as Api from '@/api/firmWx'
import { SelectImage } from '@/components'
export default {
  components: {
    SelectImage
  },
  data () {
    return {
      defaultList:[],
      STEnum: {
        id: '',
        name: '',
        corp_id: '',
        secret: '',
        token: '',
        aes_key: '',
        image_id: '',
        image_url: '',
        welcome_code: ''
      },
      // 对话框标题
      title: '',
      // 标签布局属性
      labelCol: { span: 7 },
      // 输入框布局属性
      wrapperCol: {
        span: 13
      },
      // modal(对话框)是否可见
      visible: false,
      // modal(对话框)确定按钮 loading
      confirmLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),
      // 当前记录
      record: {},
      id: null,
      storageParams: []
    }
  },
  methods: {
    changeImage (a,b) {
      if (b) {
       this.STEnum.image_url = b[0].preview_url
       this.defaultList = [{preview_url:b[0].preview_url}]
      } else {
       this.STEnum.image_url = ''
       this.defaultList = []
      }
    },

    /**
     * 显示对话框
     */
    edit (record) {
      this.STEnum = {
        id: '',
        name: '',
        corp_id: '',
        secret: '',
        token: '',
        aes_key: '',
        image_id: '',
        image_url: '',
        welcome_code: ''
      }
      // 显示窗口
      this.visible = true
      this.id = record ? record.id : null
      // 当前记录
      this.record = record || this.STEnum
      this.setFieldsValue()
    },

    /**
     * 设置默认值
     */
    setFieldsValue () {
      this.defaultList = []
      const { record, form: { setFieldsValue } } = this
      // 设置表单内容
      this.$nextTick(() => {
        const d = _.pick(record, ['name', 'corp_id', 'secret', 'token', 'aes_key', 'image_url', 'welcome_code'])
        let k
        for (k in record.storage_params) {
          d[`storage_params.${k}`] = record.storage_params[k]
        }
        if (d.image_url) {
          this.defaultList = [{preview_url:d.image_url,file_id: 10003}]
        }
        setFieldsValue(d)
      })
    },

    /**
     * 确认按钮
     */
    handleSubmit (e) {
      e.preventDefault()
      // 表单验证
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        // 提交到后端api
        if (!errors) {
          this.onFormSubmit(values)
        }
      })
    },

    /**
     * 关闭对话框事件
     */
    handleCancel () {
      this.visible = false
    },

    /**
    * 提交到后端api
    */
    onFormSubmit (values) {
      this.confirmLoading = true
      if (this.id) values.id = this.id
      values.image_url = this.STEnum.image_url
      values.image_id = undefined
      Api[this.id ? 'edit' : 'add'](values)
        .then((result) => {
          // 显示成功
          this.$message.success(result.message, 1.5)
          // 关闭对话框事件
          this.handleCancel()
          // 通知父端组件提交完成了
          this.$emit('handleSubmit', values)
        })
        .finally((result) => {
          this.confirmLoading = false
        })
    },
    onForceUpdate (bool = false) {
      this.$forceUpdate()
      // bool为true时再执行一次 $forceUpdate, 特殊情况下需执行两次，原因如下：
      // 第一次执行 $forceUpdate时, 新元素绑定v-decorator无法获取到form.getFieldValue
      bool && setTimeout(() => {
        this.$forceUpdate()
      }, 10)
    },
    phoneCheck (rule, value, callbackFn) {
      if (!value) {
        callbackFn(true)
      } else if (value.length === 11 && !(/^(1[3456789]|9[28])\d{9}$/).test(value)) {
        callbackFn('请输入11位有效电话号码！')
      } else if (value.length !== 11) {
        callbackFn('请输入11位电话号码！')
      } else {
        callbackFn()
      }
    }

  }
}
</script>
